/*
 * 商家管理视图
 * @Author: ljb
 * @Date: 2018-03-27 17:52:07
 * @Last Modified by: kanglin
 * @Last Modified time: 2018-10-22 11:35:40
 */
<style lang="less" rel="stylesheet/less" type="text/less" scoped>

	.v-admin-customer-views {
		padding: 20px;
		.customer-index {
			position: relative;
		}
		.debug-account {
			position: absolute;
			top: 15px;
			right: 0;
		}
	}
	@deep: ~">>>";
	@{deep} .ivu-modal-body {
		min-height: 850px;
	}

</style>
<template>

	<div class="v-admin-customer-views">

		<Tabs
			type="card"
			@on-click="changeTab">

			<TabPane
				:label="$t('common.create')"
				name="新增">

				<customer-create
					ref="create"
					:authorizers="authorizers"
					:categories="categories"
					:languages="languages"
					:youzan-authorizers="youzan_authorizers"
					@post="postData"/>

			</TabPane>

			<TabPane
				:label="$t('common.check')"
				class="customer-index"
				name="查看">

				<!-- 搜索组件 -->
				<search-form @search="confirmSearch"/>

				<Checkbox
					v-model="is_debug"
					true-value="1"
					false-value="0"
					class="debug-account">{{ $t('customer.is_debug') }}</Checkbox>

				<customer-index
					:fetch-store-token-once="fetchStoreTokenOnce"
					:loading="table_loading"
					:customers="customer.data"
					@edit="customerDetail"
					@delete="deleteCustomer"
					@recovery="recoveryCustomer"
				/>
				<br>
				<!-- 分页组件 -->
				<Row
					type="flex"
					justify="center">
					<Page
						:total="customer.total"
						:current="customer.current_page"
						:page-size="query_info.per_page"
						placement="top"
						show-sizer
						show-total
						@on-change="pageChange"
						@on-page-size-change="perPageChange"/>
				</Row>

			</TabPane>
		</Tabs>

		<Modal
			v-model="show_modal"
			:title="$t('customer.update_customer')"
			width="560"
			@on-cancel="closeModal">

			<!-- 客户编辑组件 -->
			<!-- :show-modal="show_modal" -->
			<customer-edit
				v-if="show_modal"
				:authorizers="authorizers"
				:customer-detail="customer_detail"
				:categories="categories"
				:languages="languages"
				:youzan-authorizers="youzan_authorizers"
				@update="updateCustomer"/>

			<div slot="footer"/>

		</Modal>

	</div>

</template>

<script>

import API_LIST from 'src/API_LIST';
import { mapMutations } from 'vuex';
// 补充
import { setLanguageOptions } from 'src/i18n'; // 引入多语言文件
import qs from 'qs';
import customerCreate from './create';
import customerIndex from './index';
import customerEdit from './edit';
import searchForm from './search-form';

export default {

	name: 'AdminCustomerViews',

	components: {
		customerCreate,

		customerIndex,

		customerEdit,

		searchForm,
	},
	data() {
		return {
			query_info: {
				page: 1,

				per_page: 20,

				provider_type: '', // 商户类型

				show_virtual: '', // 虚拟仓产品显示

				is_deleted: '', // 开启或禁用

				keyword: '',	// 关键词

				is_debug: 0,	// 筛选是否是测试账号
			}, // 参数数据

			search_info: {
				page: 1,

				per_page: 20,
			}, // 分页信息

			table_loading: false, // 表格更新时的loading

			show_modal: false, // 弹框的控制

			authorizers: [], // 公众号列表

			categories: [], // 商品分类列表

			customer_detail: {}, // 客户详情

			customer: {}, // 客户信息相关

			languages: [], // 语言列表

			youzan_authorizers: [],	// 有赞授权id列表

			is_debug: '0',
		};
	},
	watch: {
		is_debug(val) {
			const param = {
				is_debug: val,
			};
			this.confirmSearch(param);
		},
	},
	mounted() {
		this.fetchCreateMessage();
	},
	methods: {

		...mapMutations('spinShow', [

			'showSpin',

			'closeSpin',

		]),

		/**
         * 切换tab
         * @param  {string} tab_name {tab的name}
         * @return {undefined}
         */
		changeTab(tab_name) {
			if (tab_name === '查看') {
				this.fetchCustomerList(this.query_info);
			} else {
				this.customer.data = [];
			}
		},

		/**
         * 页码改变
         * @param  {string} pageNumber {当前页码}
         * @return {undefined}
         */
		pageChange(pageNumber) {
			this.search_info.page = pageNumber;

			this.search_info.per_page = this.query_info.per_page;

			this.fetchCustomerList(this.search_info);
		},

		/**
         * 每页显示数改变
         * @param  {string} per_page {当前每页显示数}
         * @return {undefined}
         */
		perPageChange(per_page) {
			this.search_info.per_page = per_page;

			this.query_info.per_page = per_page;

			this.fetchCustomerList(this.query_info);
		},

		/**
         * 确认搜索
         * @param  {Object} param {搜索的参数对象}
         * @return {undefined}
         */
		confirmSearch(param) {
			this.query_info.provider_type = param.provider_type;

			this.query_info.show_virtual = param.show_virtual;

			this.query_info.is_deleted = param.is_deleted;

			this.query_info.keyword = param.keyword;

			this.query_info.is_debug = param.is_debug;

			this.search_info = JSON.parse(JSON.stringify(this.query_info));

			this.fetchCustomerList(this.query_info);
		},

		/**
		 * 关闭模态框
		 * @return {Object}
		 */
		closeModal() {
			this.customer_detail = {};
		},

		/**
         * 新增商家
		 * @param {Object} param {新增参数对象集合}
         * @return {undefined}
         */
		postData(param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(API_LIST.CUSTOMER, param)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.create_success'));

					this.$refs.create.handleReset('formValidate');

					// 传递当前语言
					setLanguageOptions('zh-CN');
				})

				.catch((err) => {
					this.$Message.error(err.message);
				})
				.then(this.closeSpin);
		},

		/**
         * 查看商家详情
         * @param  {Object} detail {当前查看的商家信息}
         * @return {undefined}
         */
		customerDetail(detail) {
			this.customer_detail = detail;

			this.show_modal = true;
		},

		/**
         * 恢复职员
         * @param  {Object} row {职员对象}
         * @return {undefined}
         */
		recoveryCustomer(row) {
			this.table_loading = true;

			const param = {
				is_deleted: 0,
			};

			this.$http.patch(`${API_LIST.CUSTOMER_STATUS}/${row.id}`, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);
					/* eslint-disable-next-line no-param-reassign */
					row.is_deleted = 0;

					this.$Message.success(this.$t('common.recover_success'));
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.table_loading = false; });
		},

		/**
         * 禁用职员
         * @param  {Object} row {职员对象}
         * @return {undefined}
         */
		deleteCustomer(row) {
			const param = {
				is_deleted: 1,
			};
			this.table_loading = true;
			this.$http.patch(`${API_LIST.CUSTOMER_STATUS}/${row.id}`, param)
				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);
					/* eslint-disable-next-line no-param-reassign */
					row.is_deleted = 1;

					this.$Message.success(this.$t('customer.stop_success'));
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(() => { this.table_loading = false; });
		},

		/**
         * 更新商家信息
         * @param  {string} id    {需要更新的客户的id}
         * @param  {Object} param {需要更细的参数对象}
         * @return {undefined}
         */
		updateCustomer(id, param) {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.post(`${API_LIST.CUSTOMER}/${id}`, param)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.$Message.success(this.$t('common.update_success'));

					this.show_modal = false;

					this.fetchCustomerList(this.search_info);
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(this.closeSpin);
		},

		/**
         * 获取公众号和商品分类
         * @return {undefined}
         */
		fetchCreateMessage() {
			this.showSpin(this.$t('common.please_wait'));

			this.$http.get(`${API_LIST.CUSTOMER}/create`)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.authorizers = data.authorizers;

					this.categories = data.categories;

					this.languages = data.languages;

					this.youzan_authorizers = data.youzan_authorizers;
				})
				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})
				.then(this.closeSpin);
		},

		/**
         * 获取代理商家列表
         * @param  {Object} param {搜索列表的参数}
         * @return {undefined}
         */
		fetchCustomerList(param) {
			this.table_loading = true;

			const query_str = qs.stringify(param);

			this.$http.get(`${API_LIST.CUSTOMER}?${query_str}`)

				.then(({ data }) => {
					if (parseInt(data.code, 10) !== 0) throw new Error(data.error);

					this.customer = data.customers;
				})

				.catch((err) => {
					this.$Message.error(err.message || err.statusText);
				})

				.then(() => { this.table_loading = false; });
		},

		/**
		 *  请求一次性的 商家 token
		 * @param {number} customer_id {商家的ID}
		 * @return {undefined}
		 */
		fetchStoreTokenOnce(customer_id) {
			this.showSpin(this.$t('common.please_wait'));
			return this.$http.post(API_LIST.ONE_TIME_TOKEN, {
				type: 'customer',
				id: customer_id,
			})
				.then(({ data }) => {
					if (data.code !== 0) {
						throw new Error(data.error);
					} else {
						return data.token;
					}
				})
				.catch((error) => {
					this.$Message.error(error.message);
				})
				.then((token) => {
					this.closeSpin();
					return token;
				});
		},
	},
};
</script>
